<?php

namespace App\Http\Model;

use App\Lib\Snowflake\SnowflakeGenerator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class FinanceDebris extends Base
{
    protected $table = 'finance_debris_stream';
    protected $giftBag;

    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";

    public function __construct(array $attributes = [])
    {
        $this->tablePrefix = env('DB_PREFIX');
        parent::__construct($this->table, $attributes);
        $this->giftBag = new GiftBag();
    }


    /**
     * 更新用户碎片
     * @param int $userId 更新该user_id
     * @param int $dataType 数据类型 1=礼物ID 2=商品ID
     * @param int $dataId 数据ID
     * @param int $debrisType 类型 1=送彩蛋获得 
     *                  51=碎片兑换扣除
     * @param int $changeValue 变动值 支出使用负数
     * @param string $changeDesc 变动描述
     * @return bool
     */
    public function inc($userId, $dataId, $debrisType, $changeValue, $changeDesc, $value1=0){
        if(empty($userId)) {
            return false;
        }
        $dataType = 0;
        if(in_array($debrisType, [1])) {
            $dataType = 1;
        }elseif(in_array($debrisType, [51])) {
            $dataType = 2;
        }

        if(in_array($debrisType, [1])) {
            $changeValue = abs($changeValue);
        }else{
            $changeValue = 0 - abs($changeValue);
        }

        DB::table("finance_wallet")
            ->where('user_id', '=', $userId)
            ->increment('debris_balance', $changeValue, ['change_timestamp'=> time()]);

        DB::table($this->table)->insert([
            "user_id" => $userId,
            "change_value" => $changeValue,
            "change_desc" => $changeDesc,
            "debris_type" => $debrisType,
            "data_id" => $dataId,
            "data_type" => $dataType,
            "value1" => $value1,
            "change_timestamp" => time()
        ]);

        Redis::DEL($this->redis_cache_finance_user_wallet . ':' . $userId);
        return true;
    }

}
